package com.soujiayi.adapter;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import com.soujiayi.activity.TuanSelectCityActivity;
import com.soujiayi.activity.R;
import com.soujiayi.util.Constants;
import com.soujiayi.view.TuanCityGridView;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class TuanCityListAdapter extends BaseAdapter {

	private Context context;

	private LayoutInflater layoutInflater;

	private ArrayList <LinkedHashMap<String, Object>> listMap;

	public TuanCityListAdapter(Context context,
			ArrayList <LinkedHashMap<String, Object>> listMap) {
		this.context = context;

		layoutInflater = LayoutInflater.from(context);

		this.listMap = listMap;
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return this.listMap != null ? this.listMap.size() : 0;
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return this.listMap.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		if (convertView == null) {
			convertView = layoutInflater.inflate(
					R.layout.city_select_list_item, null);
		}

		TuanCityGridView gv_city_area = (TuanCityGridView) convertView
				.findViewById(R.id.gv_city_area);
		TextView tv_city_pinyin = (TextView) convertView
				.findViewById(R.id.tv_city_pinyin);

		String type = listMap.get(position).get(Constants.TUAN_CITY_AREA).toString();
		ArrayList<String> list = (ArrayList<String>) listMap.get(position).get(
				Constants.TUAN_CITY_CITIES);
		tv_city_pinyin.setText(type);
		gv_city_area.setAdapter(new ArrayAdapter<String>(context,
				R.layout.city_select_grid_item, list));
		gv_city_area.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View view, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				((Activity) context).setResult(
						Activity.RESULT_OK,
						((Activity) context).getIntent().putExtra(
								Constants.TUAN_CITY_CITYNAME,
								((TextView) view
										.findViewById(R.id.tv_city_name))
										.getText().toString()));
				((Activity) context).finish();
			}

		});

		return convertView;
	}

}
